package transporte.util;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import transporte.server.entity.Persona;

public class JSonUtils {

	public static final String JSON_PARAM = "jsonObject";  
	
	public static String getJSonSuccessView(ModelMap model) {
		return getJSonView(model, "success");
	}
	
	public static String getJSonFailView(ModelMap model) {
		return getJSonView(model, "fail");		
	}

	/**
     * @author spulido
     * @param model
     * @return
     */
    public static String getJSonView(ModelMap model, String result) {
	    try {
			JSONObject object = new JSONObject();
	        object.put("result", result);
	        return getJSonView(model, object);
        } catch (JSONException e) {
	        throw new RuntimeException(e);
        }
    }
	
	public static String getJSonView(ModelMap model, JSONObject object) {
		
		model.put(JSON_PARAM, object);
		
		return "/ajax/jsonResponse";
	}
	
	public static ModelAndView getJSonModelAndView(Map<String, Object> model, JSONObject object) {
		
		model.put(JSON_PARAM, object);
		
		return new ModelAndView("/ajax/jsonResponse", model);
	}
	
	public static String getJSonPersonaView(ModelMap model, Persona persona) {
		try {
			JSONObject object = new JSONObject();
			//quien necesite mas datos puede agregarlos del objeto persona
			if(persona!=null){
				object.put("existe", "true");
				object.put("idPersona", persona.getIdPersona());
				object.put("numeroIdPersona", persona.getNmidentificacion());
				object.put("tipoIdPersona", persona.getTipoIdentificacion().getIdTipoIdentificacion());
				object.put("primerNombrePersona", persona.getPrimerNombre());
				object.put("segundoNombrePersona", persona.getSegundoNombre()==null?"":persona.getSegundoNombre());
				object.put("primerApellidoPersona", persona.getPrimerApellido());
				object.put("segundoApellidoPersona", persona.getSegundoApellido()==null?"":persona.getSegundoApellido());
			}else{
				object.put("existe", "false");
				object.put("idPersona", "");
				object.put("numeroIdPersona", "");
				object.put("tipoIdPersona", "");
				object.put("primerNombrePersona", "");
				object.put("segundoNombrePersona", "");
				object.put("primerApellidoPersona", "");
				object.put("segundoApellidoPersona", "");
			}
			return getJSonView(model, object);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}
	
}
